package com.application.Activity;

import it.unipr.ce.dsg.s2p.sip.Address;

import java.util.ArrayList;

import ReadWriteXML.CMember;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;
import com.application.DTO.AccountDTO;
import com.application.DTO.RoleDTO;
import com.application.Network.Protocol;
import com.application.TextNode.BoardViewTN;
import com.application.Tree.BoardView;
import com.application.Tree.TreeNode;
//import com.application.Activity.R;

public class frmTreeNodeActivity extends Activity implements View.OnClickListener {
	/** Called when the activity is first created. */
	public static int ON_EXIT_APP=1111;
	public static int CODE_KICK = 101;
	public static int CODE_STOP_TALK = 301;
	public static String IP_RESULT = "IP_RESULT";
	public static Address ipBeingStopTalk;
	int timeStopTalk;
	public static int kickVoteResult;
	public static Address ipBeingKick;	
	public static int timeVoteKick;	
	ArrayList<CMember> memberList;
	public static ArrayList<Integer> yesVote;
	public static ArrayList<Integer> noVote;
	public static Runnable dislayKickMember;
	public static Runnable dislayKickedMessage;
	public static Runnable raShowMessage;
	public static String message;
	//============SUY NGHI LAI Co NEN DE O DAY KO?????????????====================
	
	public static Runnable raAddnode = null;
	public static Runnable raUpdateTextNode = null;
	public static Runnable raDeleteNode = null;
	public static Runnable raResetTree = null;
	LinearLayout layout;
	String value = "";
	static BoardView board = null;
	private BoardViewTN boardText;
	LayoutInflater layoutInflater;
	FrameLayout frmLayout;
	Button btnSwitch, btnSaveTree, btnDeleteAll;
	public static long idNode;
	public static String textUpdate = "";
	public static long id = 0;
	public static TreeNode nodeAdd;
	public static boolean isActive=false;
	private boolean sw=false;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_tree_node); 
		Log.d("Phu", "frmTreeNodeActivity onCreate");
		isActive=true;
		board = (BoardView) findViewById(R.id.boardID);
		boardText=(BoardViewTN)findViewById(R.id.boardtextID);
		boardText.setVisibility(View.GONE);
		//board.writeXML(BoardView.treePath);
		
		board.setVisibility(View.VISIBLE);
		board.readXml(BoardView.treePath);
		board.isActive=true;
		Log.d("Phu", "tree title:"+board.getTree().getTitle());
		raAddnode = new Runnable() {
			@Override
			public void run() {				
				board.addNode(idNode, nodeAdd, BoardView.treePath);
			}
		};
		raUpdateTextNode = new Runnable() {
			@Override
			public void run() {
				board.updateText(idNode, textUpdate, BoardView.treePath);
			}
		};
		raDeleteNode = new Runnable() {

			@Override
			public void run() {				
					Log.d("Phu", "raDeleteNode: idNode=" + idNode);		
					board.removeNodeById(idNode, BoardView.treePath);		
			}
		};
		raResetTree=new Runnable() {
			
			@Override
			public void run() {
//				resetTree();
			}
		};
		btnSwitch=(Button)findViewById(R.id.btnSwitch);
		btnSwitch.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(sw){
					board.setVisibility(View.VISIBLE);	
					boardText.setVisibility(View.GONE);
					sw=false;
				}else{
					board.setVisibility(View.GONE);
					boardText.setVisibility(View.VISIBLE);
					sw=true;
				}
			}
		});
		//====+TRUC
		
//		raShowMessage=new Runnable() {
//			
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub
//				ShowOnTree(message);
//			}
//		};
		//END TRUC========
	}

	public void showAlert() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		final EditText input = new EditText(this);
		alert.setTitle("Nhập nội dung!");
		alert.setView(input);
		alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				value = input.getText().toString();
			}
		});

		alert.show();
	}

	@Override
	public void onClick(View v) {

	}

	@Override
	public void onResume() {
		super.onResume();
		ActivityController.setPeerActivity(this);
		Log.d("Phu", "frmTreeNodeActivity onResume");
		board.readXml(BoardView.treePath);
		board.isActive=true;
		
	}
	@Override
	public void onStop() {
		super.onStop();		
		isActive=false;
		Log.d("Phu", "frmTreeNodeActivity onStop");
	}

	@Override
	public void onPause() {
		super.onPause();
		ActivityController.setPeerActivity(this);
		//isActive=false;
		isActive=true;
		board.writeXML(BoardView.treePath);
		board.isActive = false;
		
	}
	
	@Override
	public void onStart() {
		super.onStart();	
		ActivityController.setPeerActivity(this);
		isActive=true;
		board.isActive = true;
		if (board != null) {
			try {
				
				board.readXml(BoardView.treePath);
			} catch (Exception e) {
				Log.d("Phu", "ko doc duoc tree:" + e);
			}
		}
		if (NetworkController._peer == null) {
			String s = "";
			AccountDTO account = new AccountDTO();
			account.set_Username("quocphu");
			ArrayList<RoleDTO> roleList = ReadWriteFileController.readRole(null,ReadWriteFileController.MY_ROLE_PATH);

			for (RoleDTO role : roleList) {
				account.addRole(role);
				Log.i("Phu","Role: "+role.getName());
			}
			NetworkController.init("MES", Protocol.PORT, account);	
			
		}
		
		
		this.setTitle(NetworkController._peer.getAddressPeer());
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		// menu.add(Menu.NONE, NOTEPAD, Menu.NONE, "Note")
		// .setIcon(R.drawable.img_clear)
		// .setAlphabeticShortcut('e');
		// menu.add(Menu.NONE, INTERACTION, Menu.NONE, "Cộng tác")
		// .setIcon(R.drawable.img_cauhoi)
		// .setAlphabeticShortcut('f');
		// menu.add(Menu.NONE, SETTING, Menu.NONE, "Tuỳ chỉnh")
		// .setIcon(R.drawable.img_chat)
		// .setAlphabeticShortcut('g');
		// return(super.onCreateOptionsMenu(menu));
		new MenuInflater(getApplication()).inflate(R.menu.omnu_thao_luan, menu);
		return (super.onCreateOptionsMenu(menu));
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d("Phu", " vao ham onActivityResult tree");
		if (resultCode == CODE_KICK) {
			Log.d("Phu", " CODE_KICK");
			String ipKick = data.getStringExtra(IP_RESULT);
			if (ipKick != null) {
				// userNameKick = data.getStringExtra(USERNAME_BEING_KICK);
				ShowSetTimeVoteKick(ipKick);

			}
		}
		if (resultCode == CODE_STOP_TALK) {
			Log.d("Phu", " CODE_STOP_TALK");
			String ipStop = data.getStringExtra(IP_RESULT);
			if (ipStop != null) {
				// userNameStop = data.getStringExtra(USERNAME_STOP_TALK);
				ShowSetTimeStopTalking(ipStop);
			}
		}
		if (resultCode == ON_EXIT_APP) {
			 finish();
		 }
	}
	
	//============THINKING=====================
	
	public void ShowSetTimeVoteKick(final String IP) {

		Log.d("Phu", " vao ShowSetTimeVoteKick");
		Log.d("Phu", "ip kick" + IP);
		Log.d("Phu", "My ip " + NetworkController._peer.getAddressPeer());
		String s[] = IP.split(":");
 
		String ipBeKick = s[1] + ":" + s[2];
		Log.d("Phu", "ip be kick " + ipBeKick);
		if (NetworkController._peer.getAddressPeer().equals(ipBeKick)) {
			NetworkController.ShowMessageNoticeTAB("Bạn không thể làm điều này!");
		} else {
			final EditText txtTime = new EditText(this);
			txtTime.setSingleLine();
			txtTime.setInputType(2);
			AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Chọn thời gian biểu quyết")
					.setMessage("Thời gian được tính bằng giây.").setView(txtTime)
					.setPositiveButton("OK", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							String StrTime = txtTime.getText().toString();
							int time = Integer.parseInt(StrTime);
							timeVoteKick = time;
							yesVote = new ArrayList<Integer>();
							noVote = new ArrayList<Integer>();
							ipBeingKick = new Address(IP);
					//		memberList = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
//							for (CMember member : memberList) {
//								NetworkController.SendVoteKickMember(new Address(member.get_ip()), ipBeingKick, time);
//							}
							NetworkController.SendVoteKickMemberGroup("TRUC", ipBeingKick, time);
							Log.d("Phu", "Da gui xong kick");
							// dem thoi gian
							long kickTime = timeVoteKick * 1000;

							CountDownTimer timer = new CountDownTimer(kickTime, 1000) {
								@Override
								public void onTick(long millisUntilFinished) {

								}

								@Override
								public void onFinish() {
									//Toast.makeText(getBaseContext(), "het gio kick", Toast.LENGTH_SHORT).show();
									Log.w("Phu", "yes size="+yesVote.size());
									Log.w("Phu", "no size="+noVote.size());
									kickVoteResult = 0;
									if (yesVote.size() != 0 || noVote.size() != 0) {
										
										if (yesVote.size() >= noVote.size()) {
											kickVoteResult = 1;
										}
										memberList = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
										for (CMember member : memberList) {
											Log.d("Phu", "gui result toi " + member.get_ip());
											NetworkController.SendResultVoteKickMember(new Address(member.get_ip()),
													kickVoteResult, ipBeingKick);
										}
									} else {
										// NetworkController.ShowMessageNotice("Không có ai tham gia biểu quyết.");
										NetworkController.ShowMessageNoticeTAB("Không có ai tham gia biểu quyết.");
										memberList = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
										for (CMember member : memberList) {
											Log.d("Phu", "gui result toi " + member.get_ip());
											NetworkController.SendResultVoteKickMember(new Address(ipBeingKick),
													kickVoteResult, ipBeingKick);
										}
									}
								}
							}.start();
						}
					}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub

						}
					}).create();
			dlg.show();
		}
	}
	
	public void ShowSetTimeStopTalking(final String ipStop) {
		final EditText txtTimeTalk = new EditText(this);
		txtTimeTalk.setSingleLine();
		txtTimeTalk.setInputType(2);
		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Chọn thời gian buộc ngừng thảo luận")
				.setMessage("Thời gian được tính bằng giây.").setView(txtTimeTalk)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						String StrTime = txtTimeTalk.getText().toString();
						int time = Integer.parseInt(StrTime);
						timeStopTalk = time;
						ipBeingStopTalk = new Address(ipStop);
						NetworkController.GuiYeuCauNgungThaoLuan(ipBeingStopTalk, time);
						Log.d("Phu", "vao onclick ngung noi");
						long timeLong = timeStopTalk * 1000;
						Toast.makeText(getBaseContext(), timeLong + "", 1).show();
						CountDownTimer timer = new CountDownTimer(timeLong, 1000) {

							@Override
							public void onTick(long millisUntilFinished) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onFinish() {
								// TODO Auto-generated method stub
								
								NetworkController.GuiChoPhepThaoLuan(ipBeingStopTalk);
							}
						}.start();
					}

				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

					}
				}).create();
		dlg.show();
	}
	
//public void ShowOnTree(String message) {
//		
//		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Thông báo").setMessage(message)
//				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
//
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						// TODO Auto-generated method stub
//					}
//				}).create();
//		dlg.show();
//	}
	////=======END THINKING====================
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
		Log.d("PEERDROID", " vao on key down");
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setIcon(R.drawable.img_dialog);
			builder.setMessage("Bạn có chắc muốn thoát khỏi chương trình ?")
			.setCancelable(false)
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int id) {
					if(!NetworkController.isOffline())
					{
						String s = NetworkController.get_ipHost();
						NetworkController.SendMessageLogout();
//						NetworkController.peerRelease();
						//xoá danh sách hàng xóm khi thoát khỏi ứng dụng
//						ReadWriteFileController.deleteFile(ReadWriteFileController.pathNeighborsList);
						
					}
					//NetworkController.SendMessageLogout(new Address("192.168.173.20:5033"));
					Log.d("PEERDROID","Đã Thoát khỏi chương trình");
					finish();
//					System.exit(0);
				}
			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			AlertDialog alert = builder.create();
			alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255))); 
			alert.show();
			return true;
		}
		return super.onKeyDown(keyCode, event);	
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		// switch (item.getItemId()) {
		// case NOTEPAD:
		// startActivity(new Intent(this, FrmNote.class));
		// return(true);
		// case INTERACTION:
		// startActivity(new Intent(this, FrmInteraction.class));
		// return(true);
		// case SETTING:
		// startActivity(new Intent(this, PrefSetting.class));
		// return(true);
		// }

		// return super.onOptionsItemSelected(item);
		int id = item.getItemId();
		switch (id) {
		case R.id.mnuDanhSachThanhVien:
			Intent iDanhSachThanhVien = new Intent(getBaseContext(), frmDanhSachThanhVienActivity.class);
			startActivityForResult(iDanhSachThanhVien, CODE_KICK);
			break;
		case R.id.mnuChiaSeTaiLieu:
			Toast.makeText(getBaseContext(), "Chia sẻ tài liệu", 1).show();
			break;
		case R.id.mnuVaoTroCuaToi:
			Intent iVaiTro = new Intent(getBaseContext(), frmVaiTroCuaToiActivity.class);
			startActivity(iVaiTro);
			break;
		case R.id.mnuQuyenCuaToi:
			Intent iQuyen = new Intent(getBaseContext(), frmQuyenCuaToi.class);
			startActivity(iQuyen);
			break;
		default:
			break;
		}
		return true;
	}
	
	
}